import { StorageService } from './../../providers/StorageService';
import { nailerService } from './../../providers/nailerService';
import { BasePage } from './../basePage';
import { Component, Injector } from '@angular/core';
import { IonicPage, ActionSheetController } from 'ionic-angular';
import { PIC_URL } from "./../../providers/Config";
import { FileObj } from './../../model/FileObj';
import { Http, Response } from '@angular/http';
import { NativeService } from './../../providers/NativeService';
import { FileService } from './../../providers/FileService';


import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
/**
 * Generated class for the IssueImgPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-issue-img',
  templateUrl: 'issue-img.html',
})
export class IssueImgPage extends BasePage {

  imgobj: any;
  returnImgArr = [];
  returndata: string;
  imageVO = {}
  imageArrVO = [];
  fileObjList: FileObj[] = [];
  filePaths: FileObj[] = [];



  details: any;
  showSelect: boolean;
  // fileObjList: any;
  circle1Class = 'circle1';//发布美图
  picrooturl = '';
  userVo = {};//获取后台返回回来的数据
  userApi = { //需要修改的值
    "add_type": 0,
    "user_id": 0,    /**用户id */
    "service_id": 0, /**服务id */
    "nail_id": 0,   /**美甲id */
    "artist_id": 0,  /**美甲师id */
    "service_price": 0.00,
    "market_price": 0.00,
    "service_name": '',
    "tools": '',
    "material": '',
    "imgs": '',
    "is_buy": 0,
    "consuming_time": 0
  };
  //发布新服务
  userApi2 = { //需要修改的值
    "add_type": 0,
    "user_id": 0,    /**用户id */
    "service_price": 0.00,
    "market_price": 0.00,
    "service_name": '',
    "tools": '',
    "material": '',
    "imgs": '',
    "is_buy": 0,
    "consuming_time": 0
  };
  /**发布服务所需参数 （定稿后更改） */
  issueServeiceVo = {
    type: null,
    shop_id: null,
    service_id: null,
    service_price: null,
    market_price: null,
    service_name: '',
    tools: '',
    material: '',
    imgs: '/Uploads/nail_album/2017-05-24/592515487bcfe_thumb_328-340.jpg',
    consuming_time: null,//分钟为单位
    applicable_scene: '',
    service_desc: '',
    keep_time: null
  }


  userinfo: {};

  imgarr = []/**存储图片数组 */
  serve1 = 'assets/img/picbj.png'
  oper: 1;
  deleteVo = {
    file: ''
  }
  constructor(
    injector: Injector,
    private http: Http,
    private fileService: FileService,
    public actionSheetCtrl: ActionSheetController,
    public nailerservice: nailerService,
    public transfer: Transfer,
    public file: File,
    public filePath: FilePath,
    private nativeService: NativeService,
    public storage: StorageService) {
    super(injector);
    this.picrooturl = PIC_URL;


    this.http.get('./assets/data/fileData.json').map((res: Response) => res.json()).subscribe(res => {
      if (res.success) {
        for (const fileObj of res.data) {
          this.fileObjList.push({
            'thumbPath': fileObj.base64,
            'origPath': fileObj.base64,
            'base64': fileObj.base64
          });
        }
      }
    });


  }


  detailsdetails(url) {
    this.nativeService.openUrlByBrowser(url);
  }

  uploadMultiByBase64() {
    this.fileService.uploadMultiByBase64(this.fileObjList).subscribe(fileList => {
      this.nativeService.showToast('成功上传' + fileList.length + '张图片');
    });
  }

  uploadMultiByFilePath() {
    this.fileService.uploadMultiByFilePath(this.filePaths).subscribe(fileList => {
      console.log(fileList)
      this.nativeService.showToast('成功上传' + fileList.length + '张图片');
    });
  }

  ionViewDidLoad() {
    this.userinfo = this.storage.read('userinfo');
    this.userApi.user_id = this.userinfo['user_id'];
    this.oper = this.navParams.get('oper');
    console.log(this.userinfo);

    console.log(this.userinfo['shop_id']);
    this.issueServeiceVo.shop_id = this.userinfo['shop_id'];

    this.issueServeiceVo.type = this.navParams.get('type');
    console.log('我的type' + this.issueServeiceVo)
    console.log('我的type' + this.issueServeiceVo.type)
    /**发布服务编辑 继续发布 */
    this.details = {};
    if (this.issueServeiceVo.type == 3 || this.issueServeiceVo.type == 2) {
      this.details = this.navParams.get('detailObj');
      console.log(this.details);
      // this.issueServeiceVo.type = 3;
      this.issueServeiceVo.shop_id = this.details.shop_id;
      this.issueServeiceVo.consuming_time = this.details.consuming_time;
      this.issueServeiceVo.imgs = this.details.imgs;
      this.issueServeiceVo.market_price = this.details.market_price;
      this.issueServeiceVo.material = this.details.material;
      this.issueServeiceVo.service_id = this.details.service_id;
      this.issueServeiceVo.service_name = this.details.service_name;
      this.issueServeiceVo.service_price = this.details.service_price;
      this.issueServeiceVo.tools = this.details.tools;
      this.issueServeiceVo.applicable_scene = this.details.applicable_scene;
      this.issueServeiceVo.service_desc = this.details.service_desc;
      this.issueServeiceVo.keep_time = this.details.keep_time;
      console.log(this.issueServeiceVo)
      // this.imgarr.push(this.issueServeiceVo.imgs);
      this.imgarr = this.issueServeiceVo.imgs.split(',');
      if (this.imgarr.length >= 3) {
        this.showSelect = true;
      } else {
        this.showSelect = false;
      }
    }


    /**2修改服务 1创建服务 */
    // if (this.oper == 1) {
    //   this.getownerself();
    // } else if (this.oper == 2) {
    //   this.getParams();
    // } else {
    //   this.editparams();
    // }

  }

  dismissCLI() {
    this.viewCtrl.dismiss(1);
  }




  // async uploadImage(imageParam) {

  //   console.log(imageParam)
  //   for (let image of imageParam) {
  //     this.imageArrVO.push(image.origPath);
  //   }
  //   console.log(this.imageArrVO);
  //   this.imageVO = Object.assign({}, this.imageArrVO)
  //   console.log(this.imageVO)
  //   let res = await this.nailerservice.uploadCommon(this.imageArrVO);
  //   console.log(res);

  // }

  async uploadImage(imageParam) {
    if(imageParam.length==0){
      return;
    }

    this.returnImgArr = [];
    this.imageArrVO = [];
    var url = 'http://192.168.1.99:7777/admin/api/uploadCommon';
    for (let image of imageParam) {
      this.imageArrVO.push(image.origPath);
    }
    console.log(this.imageArrVO);

    const fileTransfer: TransferObject = this.transfer.create();

    // var loading = super.showLoading(this.loadingCtrl, "上传中...");
    var loading = this.loadingCtrl.create({
      content: "上传中...",
      //duration: 3000,
    })
    loading.present();

    for (let i = 0; i < this.imageArrVO.length; i++) {
      //fileTransfer 上传的参数
      let options = {
        fileKey: "file",
        fileName: this.imageArrVO[i],
        httpMethod: 'post',
        chunkedMode: true,
        mimeType: "multipart/form-data",
        // params: { img: targetPath }
      };
      let targetPath = this.imageArrVO[i];
      //开始正式地上传
      fileTransfer.upload(targetPath, url, options).then(data => {
        console.log(data)
        this.returndata = data.response;
        this.imgobj = eval('(' + this.returndata.toString() + ')').toString();
        this.returnImgArr.push(this.imgobj);
        console.log(this.returnImgArr);
       
        this.returnImgArr;
      }, err => {
        loading.dismiss();
        this.toastCtrl.create({
          message: '图片上传发生错误，请重试。',
          duration: 3000,
          position: 'bottom',
        }).present();
      });
      console.log(this.returnImgArr);
      console.log("我在循环里面")
    }


    loading.dismiss();
    this.toastCtrl.create({
      message: '上传' + this.imageArrVO.length + '张图片成功。',
      duration: 3000,
      position: 'top',
    }).present();
    //在用户看清弹窗提示后进行页面的关闭

  
    console.log(this.returnImgArr);

  }

  getUploadImage(imgArr) {
    this.uploadImage(imgArr);
    setTimeout(() => {
      console.log("我是getUpLoad")
      console.log(this.returnImgArr);
      // this.imageVO = Object.assign({}, this.returnImgArr);
      this.issueServeiceVo.imgs = this.returnImgArr.join(',')
      console.log(this.issueServeiceVo.imgs)
      console.log(this.imageVO);
      this.issueServeiceVo.imgs = this.returnImgArr.toString();
      console.log(this.issueServeiceVo.imgs)
      //this.viewCtrl.dismiss(imgobj);
    }, 1000);
  }


  /**获取美甲师购买商品的服务信息 */
  getParams() {
    this.userApi.add_type = 0;
    this.userApi.service_name = this.navParams.get('nail_name');
    this.userApi.nail_id = this.navParams.get('nail_id');
    this.userApi.artist_id = this.navParams.get('seller_id');
    this.userApi.tools = this.navParams.get('tools');
    this.userApi.material = this.navParams.get('nail_materials');
    this.userApi.tools = this.navParams.get('nail_tools');
    this.userApi.service_price = this.navParams.get('order_price');
    this.userApi.is_buy = 1;
    let imgstr = this.navParams.get('nail_album');
    if (imgstr != undefined) {
      this.splitimgstr(imgstr);
    }
    delete this.userApi.service_id;
  }

  /**发布自己的服务信息 */
  getownerself() {
    this.userApi.add_type = 0;
    this.userApi.nail_id = 0;
    this.userApi.artist_id = 0;
    this.userApi.is_buy = 0;
  }


  /**编辑服务 */
  // editparams() {
  //   this.userApi.service_id = this.navParams.get('service_id');
  //   this.userApi.consuming_time = this.navParams.get('consuming_time');
  //   this.userApi.service_name = this.navParams.get('service_name');
  //   this.userApi.service_price = this.navParams.get('service_price');
  //   this.userApi.tools = this.navParams.get('tools');
  //   this.userApi.material = this.navParams.get('material');
  //   this.userApi.market_price = this.navParams.get('market_price');
  //   this.userApi.add_type = 1;
  //   this.userApi.is_buy = this.navParams.get('is_buy');
  //   this.userApi.artist_id = this.navParams.get('artist_id');
  //   let imgstr = this.navParams.get('imgs');
  //   if (imgstr != undefined) {
  //     this.splitimgstr(imgstr);
  //   }
  //   console.log(imgstr);
  //   delete this.userApi.nail_id;
  // }



  /**分割图片字符串为图片数组 */
  splitimgstr(imgstr) {
    if (imgstr.indexOf(",") != -1) {
      this.imgarr = imgstr.split(",");
    } else {
      this.imgarr[0] = imgstr;
    }
  }

  /**发布服务(是店主发布新服务) */
  async issueSevice() {
    this.getUploadImage(this.filePaths);
    console.log(this.issueServeiceVo);

    console.log(this.filePaths);
    console.log(this.issueServeiceVo)
    let res = await this.nailerservice.addShopServerAPI(this.issueServeiceVo);

    console.log(res);
    let toast = this.toastCtrl.create({
      message: res.msg,
      duration: 3000,
      position: 'top',
    })
    toast.present();
    if (res.code == 1) {
      this.viewCtrl.dismiss();
      // this.navCtrl.pop()
    }
  }



  /**发布服务(是店主发布新服务) */
  // async publicok() {
  //   this.userApi2.service_name=this.userApi.service_name;
  //   this.userApi2.service_price=this.userApi.service_price;
  //   this.userApi2.market_price=this.userApi.market_price;
  //   this.userApi2.tools=this.userApi.tools;
  //   this.userApi2.material=this.userApi.material;
  //   this.userApi2.consuming_time=this.userApi.consuming_time;
  //   this.userApi2.add_type=0;
  //   this.userApi2.user_id=this.userinfo['user_id'];
  //   this.userApi2.is_buy=0;
  //   this.userApi2.imgs=this.imgarr.toString();
  //   console.log(this.userApi2);
  //   if(this.userApi2.service_name==""||this.userApi2.service_price==0.00||this.userApi2.market_price==0.00
  //     || this.userApi2.tools=="" ||this.userApi2.consuming_time==0 ||this.userApi2.material=="" ||this.userApi2.imgs.length == 0){
  //         this.showAlert("您有未填项，请填写完整并上传图片后发布服务哦！")
  //   }else{
  //     console.log(this.userApi2);
  //     let result = await this.nailerservice.addShopServerAPI(this.userApi2);
  //     if (result.code != 1) {
  //       let toast = this.toastCtrl.create({
  //         message: result.msg,
  //         duration: 3000,
  //         position: 'top',
  //       })
  //       toast.present();
  //       return false;
  //     } else {
  //       this.showAlert('发布成功');
  //       //this.navCtrl.push('StoreShowPage');
  //       let modal = this.modalCtrl.create("StoreShowPage");
  //       modal.onDidDismiss(data => {

  //       });
  //       modal.present();
  //       }
  //   }
  // }


  /**从美甲师购买中发布美甲服务 */
  async getShopBuyNailListAPI() {
    console.log(this.userApi2);
    let result = await this.nailerservice.addShopServerAPI(this.userApi2);
    if (result.code != 1) {
      let toast = this.toastCtrl.create({
        message: result.msg,
        duration: 3000,
        position: 'top',
      })
      toast.present();
      return false;
    } else {
      this.showAlert('发布成功');
      //this.navCtrl.push('StoreShowPage');
      let modal = this.modalCtrl.create("StoreShowPage");
      modal.onDidDismiss(data => {

      });
      modal.present();
    }
  }


  presentActionSheetCamr() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择',
      buttons: [
        {
          text: '拍照上传',
          handler: () => {

          }
        }, {
          text: '从相册上传',
          handler: () => {

          }
        },

        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }
  /**删除图片 */
  async delImg(picFile, index) {
    console.log(picFile)
    console.log(index)
    this.deleteVo.file = picFile;
    let res = await this.nailerservice.delImg(this.deleteVo);
    console.log(res)

    console.log(this.imgarr)
    if (res.code == 1) {
      this.toastCtrl.create({
        message: res.msg,
        duration: 3000,
        position: 'middle'
      }).present();
      this.imgarr.splice(index, 1);
    }

  }
  /**子页面返回处理数据 */
  returnapiimg(event) {
    console.log("我是父页面");
    console.log(event);
    // this.userinfo = this.stc.read('userinfo');
    this.fileObjList = event[0];
    console.log(this.fileObjList)
    // console.log('我是data里面的数据' + this.fileObjList[0])
    // if (event.flagbs == 'circle1') {
    console.log('我后执行');
    // let serve1='assets/img/picbj.png'
    // var serve1 = this.fileObjList;
    // console.log(serve1)
    this.imgarr.push(this.fileObjList);
    console.log(this.imgarr)
    if (this.imgarr.length >= 3) {
      this.showSelect = true;
    } else {
      this.showSelect = false;
    }
  }
}
